import pygame
import random
import sys

# --- 1. 初始化和常量定义 ---
pygame.init()

# 屏幕设置
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("简易钢琴块")

# 颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (128, 128, 128)
RED = (255, 0, 0)

# 游戏参数
TILE_WIDTH = SCREEN_WIDTH // 4
TILE_HEIGHT = 80
TILE_SPACING = 5
FALL_SPEED = 5
SPAWN_RATE = 1000  # 毫秒

# 按键与列的对应关系
KEYS = {'a': 0, 's': 1, 'd': 2, 'f': 3}

# 字体（兼容Python 3.5，增加异常处理）
try:
    # 优先加载系统中的SimHei字体（避免依赖本地文件）
    font = pygame.font.SysFont("SimHei", 72)
    game_over_font = pygame.font.SysFont("SimHei", 72)
except:
    # 无中文字体时用默认字体，英文显示
    font = pygame.font.Font(None, 72)
    game_over_font = pygame.font.Font(None, 72)

# --- 2. 游戏对象 ---
class Tile:
    def __init__(self, column):
        self.x = column * (TILE_WIDTH + TILE_SPACING) + TILE_SPACING
        self.y = -TILE_HEIGHT
        self.width = TILE_WIDTH
        self.height = TILE_HEIGHT
        self.column = column
        self.hit = False

    def draw(self):
        color = GRAY if self.hit else BLACK
        pygame.draw.rect(screen, color, (self.x, self.y, self.width, self.height))
        pygame.draw.rect(screen, WHITE, (self.x, self.y, self.width, self.height), 2)

    def update(self):
        self.y += FALL_SPEED

    def is_off_screen(self):
        return self.y > SCREEN_HEIGHT

    def check_hit(self, column):
        if not self.hit and self.column == column:
            # 击中判定：方块底部超过屏幕底部100像素的判定线
            if self.y + self.height > SCREEN_HEIGHT - 100:
                self.hit = True
                return True
        return False

# --- 3. 游戏主循环 ---
def main():
    global FALL_SPEED, SPAWN_RATE  # 函数开头声明全局变量
    clock = pygame.time.Clock()
    tiles = []
    last_spawn_time = pygame.time.get_ticks()
    score = 0
    game_over = False

    while not game_over:
        current_time = pygame.time.get_ticks()
        screen.fill(WHITE)

        # --- 事件处理 ---
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                key = event.unicode.lower()
                if key in KEYS:
                    column = KEYS[key]
                    # 从最下面的方块开始检查，避免一次按击中多个
                    for tile in reversed(tiles):
                        if tile.check_hit(column):
                            score += 1
                            break

        # --- 游戏逻辑更新 ---
        # 生成新方块
        if current_time - last_spawn_time > SPAWN_RATE:
            random_column = random.randint(0, 3)
            tiles.append(Tile(random_column))
            last_spawn_time = current_time
            # 难度递进：分数每增5分，速度+1，生成间隔缩短（最低500毫秒）
            FALL_SPEED = 5 + score // 5
            SPAWN_RATE = max(500, 1000 - score * 10)

        # 更新方块位置，移除出屏方块
        for tile in tiles[:]:  # 切片创建副本，避免循环中删除报错
            tile.update()
            if tile.is_off_screen():
                if not tile.hit:
                    game_over = True  # 未击中的方块出屏，游戏结束
                tiles.remove(tile)

        # --- 绘制内容 ---
        # 绘制红色判定线
        pygame.draw.line(screen, RED, (0, SCREEN_HEIGHT - 100), 
                        (SCREEN_WIDTH, SCREEN_HEIGHT - 100), 3)
        # 绘制所有方块
        for tile in tiles:
            tile.draw()
        # 绘制分数（用str.format()兼容Python 3.5）
        score_text = font.render("分数: {}".format(score), True, BLACK)
        screen.blit(score_text, (10, 10))
        # 游戏结束提示
        if game_over:
            game_over_text = game_over_font.render("游戏结束", True, RED)
            text_rect = game_over_text.get_rect(center=(SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
            screen.blit(game_over_text, text_rect)
            pygame.display.flip()
            pygame.time.wait(3000)
            break

        pygame.display.flip()
        clock.tick(60)  # 固定60帧率

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()